package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.StudentDAOImpl;
import pojo.Student;
import utils.ApiResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/student")
public class StudentServlet extends BaseServlet {

    private final StudentDAOImpl studentDAO = new StudentDAOImpl();
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 添加
    public void addStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Student student = objectMapper.readValue(req.getReader(), Student.class);
            student.setCreatedAt(LocalDateTime.now());
            student.setUpdatedAt(LocalDateTime.now());

            int result = studentDAO.addStudent(student);
            ApiResult apiResult = new ApiResult(result > 0 ? 200 : 500, result > 0 ? "操作成功" : "操作失败", null);
            sendJsonResponse(resp, apiResult);
        } catch (Exception e) {
            handleError(resp, e);
        }
    }

    // 获取单个学生信息
    public void getStudentById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int studentId = Integer.parseInt(req.getParameter("studentId"));

        try {
            Student student = studentDAO.getStudentById(studentId);
            ApiResult apiResult = new ApiResult(200, "获取成功", student);
            sendJsonResponse(resp, apiResult);
        } catch (Exception e) {
            handleError(resp, e);
        }
    }

    // 更新学生
    public void updateStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Student student = objectMapper.readValue(req.getReader(), Student.class);
            student.setUpdatedAt(LocalDateTime.now());

            int result = studentDAO.updateStudent(student);
            ApiResult apiResult = new ApiResult(result > 0 ? 200 : 500, result > 0 ? "更新成功" : "更新失败", null);
            sendJsonResponse(resp, apiResult);
        } catch (Exception e) {
            handleError(resp, e);
        }
    }

    // 删除学生
    public void deleteStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int studentId = Integer.parseInt(req.getParameter("studentId"));

        try {
            int result = studentDAO.deleteStudent(studentId);
            ApiResult apiResult = new ApiResult(result > 0 ? 200 : 500, result > 0 ? "删除成功" : "删除失败", null);
            sendJsonResponse(resp, apiResult);
        } catch (Exception e) {
            handleError(resp, e);
        }
    }

    // 获取所有学生
    public void getAllStudents(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Student> students = studentDAO.getAllStudents();
            ApiResult apiResult = new ApiResult(200, "获取成功", students);
            sendJsonResponse(resp, apiResult);
        } catch (Exception e) {
            handleError(resp, e);
        }
    }

    // 分页获取学生
    public void getStudentsByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int page = Integer.parseInt(req.getParameter("page"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));

        try {
            List<Student> students = studentDAO.getStudentsByPage(page, pageSize);
            int totalStudents = studentDAO.getTotalStudents(); // 获取总学生数量
            int totalPages = (int) Math.ceil((double) totalStudents / pageSize); // 计算总页数
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("students", students);
            responseData.put("totalPages", totalPages);
            ApiResult apiResult = new ApiResult(200, "获取成功", responseData);
            sendJsonResponse(resp, apiResult);
        } catch (Exception e) {
            handleError(resp, e);
        }
    }


    // 模糊搜索学生并分页
    // 模糊搜索学生并分页
    public void searchStudentsByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        int page = Integer.parseInt(req.getParameter("page"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));

        try {
            List<Student> students = studentDAO.searchStudentsByName(name, page, pageSize);
            int totalStudents = studentDAO.getTotalStudentsByName(name); // 获取模糊搜索的总学生数量
            int totalPages = (int) Math.ceil((double) totalStudents / pageSize); // 计算总页数
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("students", students);
            responseData.put("totalPages", totalPages);
            ApiResult apiResult = new ApiResult(200, "获取成功", responseData);
            sendJsonResponse(resp, apiResult);
        } catch (Exception e) {
            handleError(resp, e);
        }
    }


    // 处理异常并返回错误消息
    private void handleError(HttpServletResponse resp, Exception e) throws IOException {
        ApiResult apiResult = new ApiResult(500, "服务器错误：" + e.getMessage(), null);
        e.printStackTrace();
        sendJsonResponse(resp, apiResult);
    }
}
